<div id="user_nomenclatoare_produse"></div>

<script type="text/javascript">			
	Ext.onReady(function(){	
		
		var ds_produse;
		var cm_produse;
		var sm_produse;
		var grid_user_nomenclatoare_produse;
		var w_user_introducere_produs;
		var fp_w_user_introducere_produs;
		var w_user_modificare_produs;
		var fp_w_user_modificare_produs;		
		

		function produse_add(){
			if (!w_user_introducere_produs) {
						// adaugare produs form panel	-----------------------------------------------------
						//-----------------------------------------------------------------------------------	

							fp_w_user_introducere_produs = new Ext.FormPanel({
								id: "frm-produse-add",
								labelAlign: 'top',
								bodyStyle: 'padding:5px',
								border: false,
								defaultType: 'textfield',
								items: [{
											fieldLabel: 'Nume',
											name: 'nume',
											anchor: '90%',
											allowBlank	:false,
											blankText	:'Reguli validare <br /><i>Camp obligatoriu</i>'										
										},{
											fieldLabel: 'Unitate de masura',
											name: 'um',
											anchor: '90%',
											allowBlank	:false,
											blankText	:'Reguli validare <br /><i>Camp obligatoriu</i>'										
										}
								],
								buttons:[{
											text:'Save and close',
											tooltip	:'Salvati si Inchideti',
											formBind:true,
											handler: function(){
												if (fp_w_user_introducere_produs.getForm().isValid()) {
													fp_w_user_introducere_produs.getForm().submit({
														url: "common/insertTable/" + Math.random(),
														params: {
															saferequest: true,
															table: 'produse',
															cyDep: true
														},
														waitTitle: 'Connecting',
														waitMsg: 'Validating and saving data...',
														success: function(form, action, o){
															if (action.result.code == 0) {
																Ext.MessageBox.alert('Atentie:', 'Eroare la adaugare');
																fp_w_user_introducere_produs.getForm().reset();
															}
															else 
																if (action.result.code == 1) {
																	Ext.MessageBox.alert('Mesaj:', 'Adaugare efectuata cu succes!');
																	ds_produse.reload();
																	fp_w_user_introducere_produs.getForm().reset();
																	w_user_introducere_produs.hide();
																}
														},
														failure: function(form, action, o){
															if (action.failureType == 'server') {
																Ext.Msg.alert('Warning', 'Cannot save to database!', obj.errors.reason);
															}
															else {
																Ext.Msg.alert('Warning!', 'Authentication server is unreachable!');
															}
															fp_w_user_introducere_produs.getForm().reset();
														}
													})
												}										
											}										
										},{
											text: 'Reset',
											tooltip:'Resetati',
											handler: function(){
												fp_w_user_introducere_produs.getForm().reset();
											}
										}
								]
							});			
						fp_w_user_introducere_produs.startMonitoring();
						
						// end adaugare produs form panel	-------------------------------------------------
						//-----------------------------------------------------------------------------------	
															
							w_user_introducere_produs = new Ext.Window({
								id				:'w-user-introducere-produs' + Math.random(),
								title			:'Adaugare produs',
								animateTarget	:'b-add',
								width			:400,
								height			:250,
								plain			:true,
								layout			:'fit',
								modal			:true,
								closeAction		:'hide',
								items			:fp_w_user_introducere_produs,
								loadMask		:{msg:'Loading...'},
					            buttons: [{
								    text		:'Cancel',
									tooltip		:'Renuntati',
								    handler		:function(){
										fp_w_user_introducere_produs.getForm().reset();
								        w_user_introducere_produs.hide();
								    }
								}]
						
							});								
				
			}else {}
			w_user_introducere_produs.show();	
		}
		function produse_edit(sID){
			if (!w_user_modificare_produs) {
						// editare produs form panel	-----------------------------------------------------
						//-----------------------------------------------------------------------------------	

							fp_w_user_modificare_produs = new Ext.FormPanel({
								id: "frm-produse-edit",
								labelAlign: 'top',
								bodyStyle: 'padding:5px',
								border: false,
								defaultType: 'textfield',
								items: [new Ext.form.Hidden({          
										  	fieldLabel: 'ID',  
										  	name: 'ID'
										}),{
											fieldLabel: 'Nume',
											name: 'nume',
											anchor: '90%',
											allowBlank	:false,
											blankText	:'Reguli validare <br /><i>Camp obligatoriu</i>'										
										},{
											fieldLabel: 'Unitate de masura',
											name: 'um',
											anchor: '90%',
											allowBlank	:false,
											blankText	:'Reguli validare <br /><i>Camp obligatoriu</i>'										
										}
								],
								buttons:[{
											text:'Save and close',
											tooltip	:'Salvati si Inchideti',
											formBind:true,
											handler: function(){
												if (fp_w_user_modificare_produs.getForm().isValid()) {
					           						fp_w_user_modificare_produs.getForm().submit({
													  		url: "common/updateTable/" + Math.random(),
															params:{saferequest:true,table:'produse'},
													  		waitTitle: 'Connecting..',
													  		waitMsg: 'Validating and saving data...',										
															success:function(form, action, o) {
																if(action.result.code === 0){
																	Ext.MessageBox.alert('Atentie:', 'Eroare la actualizare');
																	fp_w_user_modificare_produs.getForm().reset(); 	
																}else if(action.result.code == 1){
																		Ext.MessageBox.alert('Mesaj:', 'Actualizare efectuata cu succes!');
																		ds_produse.reload();
																		fp_w_user_modificare_produs.getForm().reset();
																		w_user_modificare_produs.hide();
																}
															},										
															failure: function(form, action, o){
									                            if(action.failureType == 'server'){
									                                Ext.Msg.alert('Warning', 'Cannot save to database!', obj.errors.reason);
									                            }else{
									                                Ext.Msg.alert('Warning!', 'Authentication server is unreachable!');
									                            }
																fp_w_user_modificare_produs.getForm().reset();	
															}
												  	})
												}										
											}										
										},{
											text: 'Reset',
											tooltip:'Resetati',
											handler: function(){
												fp_w_user_modificare_produs.getForm().reset();
											}
										}
								]
							});			
						fp_w_user_modificare_produs.startMonitoring();
						
						// end adaugare produs form panel	-------------------------------------------------
						//-----------------------------------------------------------------------------------	
															
							w_user_modificare_produs = new Ext.Window({
								id			:'w-user-modificare-produs' + Math.random(),
								title		:'Modificare produs',
								width		:400,
								height		:300,
								plain		:true,
								layout		:'fit',
								modal		:true,
								closeAction	:'hide',
								items		:fp_w_user_modificare_produs,
								loadMask	:{msg:'Loading...'},
					            buttons: [{
								    text	:'Cancel',
									tooltip	:'Renuntati',
								    handler	:function(){
										fp_w_user_modificare_produs.getForm().reset();
								        w_user_modificare_produs.hide();
								    }
								}]
						
							});								
				
			}else {}
			w_user_modificare_produs.show();	

			fp_w_user_modificare_produs.getForm().load({
				url:'common/selectTableWhere/' + Math.random(),                          
				waitMsg:'Loading',
				params:{saferequest:true,table:"produse",ID:sID}
			});	
			
		}
			
/**
 * grid
 * ************************************************************************
 */				
	    ds_produse = new Ext.data.Store({
			id			:'table_ds',
	        remoteSort	:true,
			baseParams	:{saferequest:true,table:'produse',cyDep:true},			
	        proxy: new Ext.data.HttpProxy({
	            url: 'common/getTable/' + Math.random()		
	        }),
	        reader: new Ext.data.JsonReader({
	            root: 'DS_PRODUSE',
	            totalProperty: 'totalCount',
	            id: 'ID',
	            fields: [
	                'nume', 'um', 'activ'
	            ]
	        })
	    });	

		ds_produse.setDefaultSort('nume', 'desc');
	    ds_produse.load({params:{start:0, limit:22}});		
		
		sm_produse = new Ext.grid.CheckboxSelectionModel();

	    function rdr_activ(val){
	        if(val == 1){
	            return '<span style="color:blue;">Activ</span>';
	        }else {
	            return '<span style="color:#e8e8e8;">Inactiv</span>';
	        }
	        return val;
	    }
		
	    cm_produse = new Ext.grid.ColumnModel([sm_produse,
				{header: "Nume",	dataIndex: 'nume'},
				{header: "UM",		dataIndex: 'um'},
				{header: "Activ",	dataIndex: 'activ',	renderer: rdr_activ}
		]);
    	cm_produse.defaultSortable = true;	
		
	    grid_user_nomenclatoare_produse = new Ext.grid.GridPanel({
			id:'gridproduse' + Math.random(),
	        renderTo:'user_nomenclatoare_produse',	
	        height:569,//586,						
			frame:false,
			anchor:'100%',					
	        title:'<?=$title?>',
	        store: ds_produse,
	        cm: cm_produse,
			sm: sm_produse,
	        loadMask: true,
	        viewConfig: {
	            forceFit:true
	        },
	        bbar: new Ext.PagingToolbar({
				beforePageText:'Pagina&nbsp;',
				afterPageText:'din {0}',
				firstText:'Prima pagina',
				lastText:'Ultima pagina',
				nextText:'Pagina urmatoare',
				prevText:'Pagina precedenta',   
	            pageSize: 22,
	            store: ds_produse,
	            displayInfo: true,
	            displayMsg: 'Produse {0} - {1} din {2}',
	            emptyMsg: "No records",
				plugins: new Ext.ux.Andrie.pPageSize({
					  beforeText:'',		
				      afterText: '&nbsp;inreg/pagina',
				      comboCfg: {width: 50}
				      })
			}),plugins: new Ext.ux.grid.Search({
						searchText:'Criterii',
						searchTipText:'Introduceti textul dorit...',
						iconCls:'b_search_cls',
						minChars:2,
						autoFocus:true,
						text:'Cauta dupa camp',
						mode:'remote',
						position:'top'
			}),
	        tbar:[{
				id		:'b-add',	
	            text	:'Add ',
	            tooltip	:'Adaugati',
	            iconCls	:'b_add_cls',
				handler	:produse_add
	        },'-',{
	            text	:'Disable',
	            tooltip	:'Dezactivati',
	            iconCls	:'b_delete_cls',
				handler	: function(){
					if(grid_user_nomenclatoare_produse.selModel.getCount() >= 1){
					  	Ext.MessageBox.confirm('Confirmation','Dezactivati inregistrarea selectata sau inregistrarile selectate?', function(btn){
							if (btn == 'yes') {
								var selections = grid_user_nomenclatoare_produse.selModel.getSelections();
								var prez = [];
								for (i = 0; i < grid_user_nomenclatoare_produse.selModel.getCount(); i++) {
									prez.push(selections[i].json.ID);
								}
								var encoded_array = Ext.encode(prez);
								Ext.Ajax.request({
									waitMsg: 'Va rugam asteptati',
									url: 'common/enableDisableTable/' + Math.random(),
									params: {
										saferequest	:true,
										table		:'produse',
										ids			:encoded_array,
										action		:'disable'
									},
									success: function(response){
										var result = eval(response.responseText);
										switch (result) {
											case 1:
												ds_produse.reload();
												break;
											default:
												Ext.MessageBox.alert('Warning', 'Nu puteti dezactiva toate inregistrarile selectate');
												break;
										}
									},
									failure: function(response){
										var result = response.responseText;
										Ext.MessageBox.alert('error', 'could not connect to the database. retry later');
									}
								});
							}							
						}
						);
					} else {
					  	Ext.MessageBox.alert('Warning','Pentru a dezactiva, selectati cel putin o inregistrare!');
					}
					
				}
	        },'-',{
	            text	:'Enable',
	            tooltip	:'Activati',
	            iconCls	:'b_enable_cls',
				handler	: function(){
					if(grid_user_nomenclatoare_produse.selModel.getCount() >= 1){
					  	Ext.MessageBox.confirm('Confirmation','Activati inregistrarea selectata sau inregistrarile selectate?', function(btn){
							if (btn == 'yes') {
								var selections = grid_user_nomenclatoare_produse.selModel.getSelections();
								var prez = [];
								for (i = 0; i < grid_user_nomenclatoare_produse.selModel.getCount(); i++) {
									prez.push(selections[i].json.ID);
								}
								var encoded_array = Ext.encode(prez);
								Ext.Ajax.request({
									waitMsg: 'Va rugam asteptati',
									url: 'common/enableDisableTable/' + Math.random(),
									params: {
										saferequest	:true,
										table		:'produse',
										ids			:encoded_array,
										action		:'enable'
									},
									success: function(response){
										var result = eval(response.responseText);
										switch (result) {
											case 1:
												ds_produse.reload();
												break;
											default:
												Ext.MessageBox.alert('Warning', 'Nu puteti activa toate inregistrarile selectate');
												break;
										}
									},
									failure: function(response){
										var result = response.responseText;
										Ext.MessageBox.alert('error', 'could not connect to the database. retry later');
									}
								});
							}							
						}
						);
					} else {
					  	Ext.MessageBox.alert('Warning','Pentru a dezactiva, selectati cel putin o inregistrare!');
					}
					
				}
	        }]
		});											


/**
 * 
 * @param {Object} grid
 * @param {Object} rowIndex
 * @param {Object} e
 */		
		
		grid_user_nomenclatoare_produse.on('rowdblclick', function(grid, rowIndex, e) {
			if (grid_user_nomenclatoare_produse.selModel.getCount() == 1) {
				var selection = grid_user_nomenclatoare_produse.selModel.getSelections();
				var selectedId = selection[0].id;
				//Ext.MessageBox.alert('Warning','ID: ' + selectedId);
				produse_edit(selectedId);
			} else {
			  	Ext.MessageBox.alert('Warning','Pentru a modifica, selectati doar o inregistrare!');
			}
				
		});
		
	//end on document ready				
	});	
</script>